﻿<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Text;
using System.IO;

public class Handler : AjaxHandlerBase
{
    
    DataTable dt=new DataTable();
    //stype说明： 0/1：房源管理Table,   2：楼盘字典管理Table    3：序列号管理Table  4：分配房源记录查询  
    string stype = "0";
    
    //private readonly Maticsoft.DAL.House_BaseInfo dal = new Maticsoft.DAL.House_BaseInfo();

    override public void RequestProcess(HttpContext context)
    {
        //初始化字段列表
        string FieldList = "";
        string TableFieldList = "";
          
        //定义数据记取的字符串
        double rows = double.Parse(HttpContext.Current.Request.QueryString["rows"]);
        int page = int.Parse(HttpContext.Current.Request.QueryString["page"]);
        string strwhere = HttpContext.Current.Request.QueryString["strwhere"];
        if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["stype"]))
            stype = HttpContext.Current.Request.QueryString["stype"];
        
        double total_page = 0;
        int count = 0;


        //所要查询的表名
        string TableName = "";
        //页码
        int PageIndex = int.Parse(HttpContext.Current.Request.QueryString["page"]);
        //页显示行数
        int PageSize = int.Parse(HttpContext.Current.Request.QueryString["rows"]);
        
        //条件 
        string StrWhere = strwhere;

        if (stype == "0" || stype == "1")
        {
            //欲选择字段列表 
            FieldList = "HouseId,HouseCode,BusinessKind,Status,Region,Community,BuildingArea,SalePrice_T,SalePrice_U,SalePrice_R,RentPrice,RentPrice_R,HouseUse,BuildingType,Model_Room,Cur_Floor,Direction,Fitment,Actuality,HavRentContract,OprPerson,OprDepart,IsHavekey,IsTrust,MarkCode,TraceNum,ServiceTime,Adddate";
            //子查询欲选择字段列表  
            TableFieldList = "HouseId,HouseCode,case BusinessKind when '20' then '出租' when '10' then '出售' else '租售' end,case Status when '10' then '有效' when '-10' then '无效' else '暂缓' end,Region,isnull(Community,'')+isnull(BuildingName,'')+isnull(Room,'') as Community ,BuildingArea,floor(SalePrice_T/10000) as SalePrice_T ,SalePrice_U,SalePrice_R,RentPrice,RentPrice_R,HouseUse,BuildingType,cast(isnull(Model_Room,0)AS varchar(10))+'/'+cast(isnull(Model_Hall,0)AS varchar(10)) +'/'+cast(isnull(Model_Toilet,0)AS varchar(10)) as Model_Room,cast(isnull(Cur_Floor,0)AS varchar(10))+'/'+cast(isnull(Total_Floor,0)as varchar(10))as Cur_Floor,Direction,Fitment,Actuality,case HavRentContract when 'true' then '有' else '无' end,OprPerson,OprDepart,case IsHavekey when 'true' then '有' else '无' end,case IsTrust when 'true' then '有' else '无' end,MarkCode,cast(isnull(HitNum,0)AS varchar(10))+'/'+cast(isnull(TraceNum,0)AS varchar(10))as TraceNum,Convert(varchar(10),ServiceTime,120) as ServiceTime,Adddate";
            if (strwhere.Contains("gh="))
            {
                string str = strwhere.Substring(strwhere.LastIndexOf('=')+1);
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hr = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(str);
                if(hr!=null)
                    StrWhere = strwhere.Substring(0, strwhere.LastIndexOf("gh=")) + "OprPersonId='" + hr.UserId + "'";                
                else
                    StrWhere = strwhere.Substring(0, strwhere.LastIndexOf("gh=")) + "OprPersonId=''";
            }
            if (stype == "0")
                TableName = "House_BaseInfo";
            else if (stype == "1")
                TableName = "Personal_FavorsInfo left join House_BaseInfo on HouseId=FavorId";
        }
        else if (stype == "2")
        {
            FieldList = "CommunityId,CommunityName,Region,Block,Address,CommunityUse,BuildingType,CompleteYear,AddTime";
            TableFieldList = "CommunityId,CommunityName,Region,Block,Address,CommunityUse,BuildingType,CompleteYear,Convert(varchar(10),AddTime,120) as AddTime";
            TableName = "Community_BaseInfo";
        }

        else if (stype == "3")
        {
            FieldList = "SerialNumber,CustomerAddress,CustomerName,MACAddress,ConstractPhone,Status,AddPerson,Addtime";
            TableFieldList = "SerialNumber,CustomerAddress,CustomerName,MACAddress,ConstractPhone,case Status when '1' then '有效' when '-1' then '无效' end,AddPerson,Convert(varchar(10),Addtime,120) as Addtime";
            TableName = "System_SerialNumber";
        }

        else if (stype == "4")
        {
            FieldList = "RecordID,HouseCode,HouseAddress,OldPerson,OldDepart,NowPerson,NowDepart,OperPerson,OperTime";
            TableFieldList = "RecordID,HouseCode,HouseAddress,OldPerson,OldDepart,NowPerson,NowDepart,OperPerson,OperTime";
            if (strwhere.Contains("gh="))
            {
                string str = strwhere.Substring(strwhere.LastIndexOf('=') + 1);
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hr = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(str);
                if (hr != null)
                    StrWhere = strwhere.Substring(0, strwhere.LastIndexOf("gh=")) + "OldPersonID='" + hr.UserId + "'";
                else
                    StrWhere = strwhere.Substring(0, strwhere.LastIndexOf("gh=")) + "OldPersonID=''";
            }
            TableName = "House_AllotLogs";            
        }

        //排序
        string OrderField="";
        if(stype!="1")
            OrderField = TableName + "." + HttpContext.Current.Request.QueryString["sidx"] + " " + HttpContext.Current.Request.QueryString["sord"];
        else
            OrderField = HttpContext.Current.Request.QueryString["sidx"] + " " + HttpContext.Current.Request.QueryString["sord"];

        DataSet ds = new DataSet();
        //根据sql执行查询
        if (stype == "3")
            ds = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
        else
            ds = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);

        count = (int)ds.Tables[1].Rows[0][0];

        //数据开始转换
        DataTable dt = ds.Tables[0];
       // dt.Load(dr);
        if(count>0)
           total_page = Math.Ceiling(count/rows);
        if(page>total_page)
           page = int.Parse(total_page.ToString());
        
        //转成json数据,这里是关键的函数此方法我是放入的一个JSON操作类中的
        string jsonData = GetJson(dt,rows,page,count,stype);


        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(jsonData);//返回json数据
    }

    public static string GetJson(DataTable dt, double rows, int page, int count,string stype)
    {
        string id="";
        if (stype == "1" || stype == "0")
            id = "HouseId";
        else if (stype == "2")
            id = "CommunityId";
        else if (stype == "3")
            id = "SerialNumber";
        else if (stype == "4")
            id = "RecordID";
        StringBuilder jsonBuilder = new StringBuilder();
        //jsonBuilder.Append("\"");
        jsonBuilder.Append("{\"page\":" + page + ",\"total\":" + Math.Ceiling(count / rows) + ",\"records\":" + count + ",\"rows\"");
        jsonBuilder.Append(":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{\"id\":\"" + dt.Rows[i][id].ToString() + "\",\"cell\":[");
            for (int j = 1; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]},");
        }
        if(dt.Rows.Count>0)
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }
}